<template>
    <div>
        <div class="">
            <el-form inline :model="queryData">
                <el-form-item label="题目ID" prop="questionid">
                    <el-input v-model.trim="queryData.questionid" clearable />
                </el-form-item>
                <el-form-item label="" prop="result">
                    <el-checkbox v-model="checkboxValue" clearable border label="测试成功" />
                </el-form-item>
                <el-form-item>
                    <el-button @click="start" type="primary">查询</el-button>
                    <el-button @click="dialogVisible = true" type="danger">创建任务</el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-table v-loading="loading" border :data="tableData" height="80vh" style="width: 100%">
            <el-table-column prop="ID" label="ID" width="80" />
            <el-table-column prop="questionid" label="题目ID" width="100" />
            <el-table-column prop="question.name" label="题目名称" width="" show-overflow-tooltip>
                <template #default="{ row }">
                    <el-link type="primary" @click="showQuestion(row.questionid)">
                        {{ row?.question.name }}
                    </el-link>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="createdAt" label="创建时间" :formatter="({ createdAt }) => TimeYH(createdAt)"
                width="160" />
            <el-table-column prop="updatedAt" label="更新时间" :formatter="({ updatedAt }) => TimeYH(updatedAt)"
                width="160" /> -->
            <el-table-column prop="step" label="步骤" width="120">
                <template #default="{ row }">
                    <el-button type="primary" @click="showDetail(row, 'step')"> 查看步骤 </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="code" label="代码" width="120">
                <template #default="{ row }">
                    <el-button type="primary" @click="showDetail(row, 'code')"> 查看代码 </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="state" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.result ? 'success' : 'danger'"> {{ row.state }} </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="lang" label="语言" width="80" />
            <el-table-column prop="resultdataarr" label="评测结果" width="">
                <template #default="{ row }">
                    <div class="submission-table">
                        <span v-if="Array.isArray(row.resultdataarr)">
                            <span v-for="(v, key) in acgroup(row.resultdataarr)" :key="'a_' + key"
                                :style="{ display: 'inline-block' }">
                                &nbsp;
                                <span :class="ALLTYPE[v[0]][1]">
                                    {{ v[0] }}:{{ v[1] }}
                                </span>
                            </span>
                        </span>
                    </div>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="mongooseId" label="mongooseId" width="" /> -->
            <el-table-column prop="message" label="报错信息" width="100" />
            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button-group>
                        <el-button type="danger" @click="del(row?.ID)">删除</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination class="pager" :page-size="limit" :page-sizes="pageSizes" :total="totalCount"
            layout="total, sizes, prev, pager, next" @current-change="changePage" @size-change="handleSizeChange"
            :current-page="Math.floor(offset / limit) + 1" />

        <!-- 题目内容弹窗 -->
        <el-dialog align-center v-model="questionVisible" width="70%">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    {{ question?.ID }} - {{ question?.name }} - 题目详情
                </span>
            </template>
            <ContextList v-bind="{ question }"></ContextList>
        </el-dialog>

        <!-- 步骤/代码详情弹窗 -->
        <el-dialog align-center v-model="detailVisible" :title="detailTitle" width="70%" class="solution-dialog">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    {{ detailTitle }}
                </span>
            </template>
            <div v-if="currentDetailType === 'step'" class="step-detail">
                <div class="solution-header">
                    <h3>{{ currentSolution.questionid }}-{{ currentSolution.question?.name || '未知题目' }}</h3>
                    <div class="meta-tags">
                        <el-tag size="small">{{ currentSolution.lang }}</el-tag>
                        <el-tag size="small" type="info">AI生成</el-tag>
                    </div>
                </div>

                <div class="step-viewer">
                    <div class="step-content" v-html="renderMarkdown(formattedSteps)" />
                </div>
            </div>

            <div v-if="currentDetailType === 'code'" class="code-detail">
                <div class="solution-header">
                    <h3>{{ currentSolution.questionid }}-{{ currentSolution.question?.name || '未知题目' }}</h3>
                    <div class="meta-tags">
                        <el-tag size="small">{{ currentSolution.lang }}</el-tag>&nbsp;
                        <el-button size="small" type="primary" plain @click="copyToClipboard(currentDetailContent)"
                            :icon="DocumentCopy">
                            复制代码
                        </el-button>
                    </div>
                </div>

                <pre v-highlight><code :class="'language-' + currentDetailLang">{{ currentDetailContent }}</code></pre>
            </div>

            <template #footer>
                <el-button @click="detailVisible = false">关闭</el-button>
            </template>
        </el-dialog>

        <!-- 创建任务弹窗 -->
        <el-dialog align-center v-model="dialogVisible" width="600" @close="close">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    AI题目题解任务
                </span>
            </template>
            <el-form ref="formDataRef" :model="formData" label-width="auto">
                <el-form-item label="题目ID范围" prop="questionidStart">
                    <el-input-number v-model="formData.questionidStart" placeholder="起始ID" :min="1" />
                    <span style="padding: 0 10px;">至</span>
                    <el-input-number v-model="formData.questionidEnd" placeholder="结束ID" prop="questionidEnd"
                        :min="1" />
                </el-form-item>
                <el-form-item label="题库ID" prop="questionbankid">
                    <el-input-number v-model="formData.questionbankid" :min="1" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" size="default" @click="submit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { DocumentCopy, Guide } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import 'highlight.js/styles/github.css';
import { countBy } from "lodash-es";
import { marked } from 'marked';
import { pairs } from "underscore";
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncCreateaccoder, asyncDelacaicontent, asyncgetquestion, asyncSelectacaicontent } from "../../../api";
import ContextList from '../../../components/watchquestion/contextlist.vue';
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { markdownhtml } from '../../../util/htmlstring';
import { ALLTYPE } from "@/util/jianchatime";

const router = useRouter();
const route = useRoute();
const store = useStore(Storekey);

// 数据查询相关
const loading = ref(false);
const queryData = ref<Studycodemodel.Iacaicontent>({ result: true });
// 计算属性处理true/undefined转换
const checkboxValue = computed({
    get() {
        return queryData.value.result === true
    },
    set(newValue) {
        queryData.value.result = newValue ? true : undefined
    }
})

const offset = ref<number>(0);
const limit = ref<number>(20);
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500]
const totalCount = ref<number>(0);
const tableData = ref<Studycodemodel.Iacaicontent[]>([]);

// 详情弹窗相关
const detailVisible = ref(false);
const currentDetailContent = ref('');
const currentDetailType = ref<'step' | 'code'>('step');
const currentDetailLang = ref('cpp');
const detailTitle = ref('');
const currentSolution = ref<any>({});

// 格式化步骤
const formattedSteps = computed(() => {
    if (!currentSolution.value?.step) return '';
    // return currentSolution.value.step;
    return formatSteps(currentSolution.value.step).join('\n\n');
});

// 创建任务相关
const dialogVisible = ref(false);
const formDataRef = ref<FormInstance>();
const formData = ref({
    questionidStart: 100014,
    questionidEnd: 100015,
    questionbankid: undefined as number | undefined
});

// 方法
async function start() {
    try {
        loading.value = true;
        const { rows, count } = await asyncSelectacaicontent({
            ...queryData.value,
            _offset: offset.value,
            _limit: limit.value,
            _sortable: "DESC"
        });
        tableData.value = rows;
        totalCount.value = count;
    } catch (error) {
        console.error(error);
        ElMessage.error('获取数据失败');
    } finally {
        loading.value = false;
    }
}

function changePage(r: number) {
    offset.value = (r - 1) * limit.value;
    start();
}
const handleSizeChange = (val: number) => {
    limit.value = val
    start()
}

async function del(ID: number) {
    try {
        await ElMessageBox.confirm(`确定删除此题解?`, '提示', {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        });
        await asyncDelacaicontent({ ID });
        start();
        ElMessage.success("操作成功");
    } catch (error) {
        console.error(error);
    }
}

async function submit() {
    try {
        const { questionidStart, questionidEnd, questionbankid } = formData.value;
        if (questionidStart || questionidEnd) {
            if (!questionidStart) throw new Error('请输入起始题目ID');
            if (!questionidEnd) throw new Error('请输入结束题目ID');
        }
        if (!questionbankid && (!questionidStart || !questionidEnd)) {
            throw new Error('必须填写完整的题目ID范围或题库ID');
        }

        const requestData = {
            questionbankid: formData.value.questionbankid,
            questionid: [formData.value.questionidStart, formData.value.questionidEnd] as [number | undefined, number | undefined]
        };

        await asyncCreateaccoder(requestData);
        ElMessage.success('任务创建成功');
        dialogVisible.value = false;
        start();
    } catch (error) {
        if (error instanceof Error) {
            ElMessage.error(error.message || '提交失败');
        }
    }
}

function close() {
    formDataRef.value?.resetFields();
}

function acgroup(data?: Array<keyof Studycodemodel.IALLTYPE>) {
    if (Array.isArray(data)) {
        const c = countBy(data, (a) => a);
        return pairs(c);
    }
    return [];
}

// 详情弹窗方法
function showDetail(row: any, type: 'step' | 'code') {
    currentSolution.value = row;
    currentDetailType.value = type;
    currentDetailContent.value = row[type];
    currentDetailLang.value = row.lang?.toLowerCase() || 'cpp';

    detailTitle.value = type === 'step' ? '解题步骤详情' : '代码详情';
    detailVisible.value = true;
}

function formatSteps(steps: any): string[] {
    if (Array.isArray(steps)) return steps;
    try {
        const parsed = JSON.parse(steps);
        return Array.isArray(parsed) ? parsed : [steps];
    } catch (e) {
        return [steps];
    }
}

function renderMarkdown(content: string): string {
    // console.log("content", content)
    if (typeof content !== 'string') {
        try {
            content = JSON.stringify(content, null, 2);
        } catch {
            content = String(content);
        }
    }
    return marked.parse(content);

    return content
        // 处理无序列表
        .replace(/^\s*-\s+(.*$)/gm, '<li>$1</li>')
        .replace(/(<li>.*<\/li>)+/g, '<ul>$&</ul>')
        // 处理有序列表
        .replace(/^\s*\d+\.\s+(.*$)/gm, '<li>$1</li>')
        .replace(/(<li>.*<\/li>)+/g, '<ol>$&</ol>')
        // 其他原有处理...
        .replace(/### (.*?)(\n|$)/g, '<h3 class="step-h3">$1</h3>')
        .replace(/## (.*?)(\n|$)/g, '<h2 class="step-h2">$1</h2>')
        .replace(/# (.*?)(\n|$)/g, '<h1 class="step-h1">$1</h1>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`(.*?)`/g, '<code class="inline-code">$1</code>');
}

function copyToClipboard(text: string) {
    try {
        navigator.clipboard.writeText(text);
        ElMessage.success('已复制到剪贴板');
    } catch (err) {
        console.error('Failed to copy: ', err);
        ElMessage.error('复制失败');
    }
}

onMounted(() => {
    start();
});

const questionVisible = ref(false)
const question = ref<Studycodemodel.Iquestion>({})
async function showQuestion(questionid: number) {
    questionVisible.value = true
    await getQuestion(questionid)
}
async function getQuestion(id: number) {
    const e = await asyncgetquestion({ ID: id })
    const data = markdownhtml(e) as Studycodemodel.Iquestion
    question.value = data;
}
</script>

<style scoped>
/* 基础样式 */
.pager {
    margin-top: 16px;
    justify-content: flex-end;
}

.submission-table .el-tag {
    width: 90px;
    border-radius: 4px;
    border: none;
}

/* 详情弹窗样式 */
.solution-dialog {
    max-height: 80vh;
    display: flex;
    flex-direction: column;
}

.solution-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;
}

.solution-header h3 {
    margin: 0;
    font-size: 18px;
    color: #303133;
}

.meta-tags {
    display: flex;
    gap: 8px;
    align-items: center;
}

/* 步骤查看器样式 */
.step-viewer {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.step-content {
    padding: 16px;
    background: #fff;
    border-radius: 4px;
    line-height: 1.6;
    max-height: 60vh;
    overflow-y: auto;
}

/* 代码查看器样式 */
.code-detail pre {
    margin: 0;
    background: #f6f8fa;
    padding: 16px;
    border-radius: 4px;
    overflow: auto;
    max-height: 60vh;
}

/* Markdown内容样式 */
.step-content :deep(h1) {
    font-size: 18px;
    color: #303133;
    margin: 16px 0 8px;
    font-weight: 500;
}

.step-content :deep(h2) {
    font-size: 16px;
    color: #409EFF;
    margin: 14px 0 8px;
    font-weight: 500;
}

.step-content :deep(h3) {
    font-size: 15px;
    color: #67C23A;
    margin: 12px 0 8px;
    font-weight: 500;
}

.step-content :deep(p) {
    margin: 8px 0;
    color: #606266;
}

.step-content :deep(ul),
.step-content :deep(ol) {
    margin: 8px 0;
    padding-left: 24px;
}

.step-content :deep(li) {
    margin: 6px 0;
}

.step-content :deep(.inline-code) {
    font-family: 'Courier New', monospace;
    background: #f5f7fa;
    padding: 2px 4px;
    border-radius: 3px;
    color: #e96900;
    font-size: 85%;
}

.step-content :deep(strong) {
    color: #303133;
}

.step-content :deep(em) {
    color: #606266;
    font-style: italic;
}
</style>